<template>
  <XenListPage
    title="辞退处理"
    :dataList="dismissRequestList"
    :visibleFields="visibleFields"
    :filterFields="filterFields"
    :actions="actions"
    :themeConfig="themeConfig"
    :loading="loading"
    :enableAutoRefresh="false"
    :enableSilentRefresh="true"
    :silentRefreshFn="silentRefreshFn"
    searchPlaceholder="点击筛选辞退处理信息"
    emptyText="暂无辞退处理信息"
    emptyDesc="暂无数据"
    detailPagePath="/subpkg-hr-syshrdismissrequestbill/details"
    permission-module="syshrdismissrequestbill"
    :showAddButton="false"
    @filter="handleFilter"
    @refresh="handleRefresh"
    @silent-refresh="handleSilentRefresh"
  >
    <!-- 自定义插槽图标 -->
    <template #search-icon>
      <uni-icons type="search" size="18" color="#999"></uni-icons>
    </template>
    <template #loading-icon>
      <uni-icons type="spinner-cycle" size="24" color="#666"></uni-icons>
    </template>
    <template #empty-icon>
      <uni-icons type="info" size="48" color="#ccc"></uni-icons>
    </template>
    <template #action-icon-view>
      <uni-icons type="eye" size="16" color="#7881de"></uni-icons>
    </template>
  </XenListPage>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import XenListPage from "@/layouts/XenListPage.vue";
import SysHrDismissRequestBillApi from "./api/index";
import commonApi from "@/api/common";
import { processDateRangeField } from "@/utils/dateRangeUtils";
import { formatDateTime } from "@/utils/xenUtils";
import type { ISysHrDismissRequestBillView } from "./api/interface";

// 创建API实例
const api = SysHrDismissRequestBillApi();
const commonApiInstance = commonApi();

// 数据列表
const dismissRequestList = ref<ISysHrDismissRequestBillView[]>([]);

// 主题配置
const themeConfig = {
  primaryColor: "#7881de",
  secondaryColor: "#764ba2",
  gradientStart: "#667eea",
  gradientEnd: "#764ba2",
};

// 定义列表显示字段
const visibleFields = [
  {
    key: "PersonName",
    label: "员工",
    formatter: (value: any) => value || "",
  },
  {
    key: "GroupName",
    label: "所属部门",
    formatter: (value: any) => value || "",
  },
  {
    key: "ResignType",
    label: "辞退类型",
    formatter: (value: any) => value || "",
  },
  {
    key: "DismissDate",
    label: "辞退日期",
    formatter: (value: any) => {
      if (!value) return "";
      const formattedDateTime = formatDateTime(value);
      return formattedDateTime ? formattedDateTime.split(" ")[0] : "";
    },
  },
  {
    key: "BillCode",
    label: "单据编号",
    formatter: (value: any) => value || "",
  },
  {
    key: "BillStatus",
    label: "单据状态",
    formatter: (value: any) => value || "",
  },
  {
    key: "Approver",
    label: "审批人",
    formatter: (value: any) => value || "",
  },
  {
    key: "ApprovalTime",
    label: "审批时间",
    formatter: (value: any) => {
      return formatDateTime(value);
    },
  },
  {
    key: "WorkflowStatus",
    label: "状态",
    type: "badge",
    formatter: (value: any) => value || "",
    badgeConfig: {
      colorMap: {
        待提交: "gray",
        提交中: "blue",
        审核中: "orange",
        已完成: "green",
        已取消: "red",
      },
      defaultColor: "gray",
      prefix: "badge-",
    },
  },
  {
    key: "Remark",
    label: "备注",
    formatter: (value: any) => value || "",
  },
  {
    key: "Describe",
    label: "辞退说明",
    formatter: (value: any) => value || "",
  },
];

// 定义搜索筛选字段
const filterFields: any[] = [
  {
    key: "Name",
    label: "员工",
    placeholder: "请输入员工姓名",
  },
  {
    key: "dismissDate",
    label: "辞退日期",
    type: "daterange",
    placeholder: "请选择辞退日期范围",
  },
  {
    key: "resignType",
    label: "辞退类型",
    type: "selector",
    placeholder: "请选择辞退类型",
    options: [
      "试用期不合格",
      "严重违纪",
      "严重失职或舞弊",
      "兼岗影响履职且拒不改正",
      "欺诈入职或合同无效",
      "刑事责任",
      "违反保密或竞业",
      "其他",
    ],
  },
  {
    key: "approver",
    label: "审批人",
    placeholder: "请输入审批人",
  },
  {
    key: "approvalTime",
    label: "审批时间",
    type: "daterange",
    placeholder: "请选择审批时间范围",
  },
  {
    key: "groupId",
    label: "所属部门",
    type: "department-picker",
    placeholder: "请选择所属部门",
    popupTitle: "选择部门",
    departmentData: [], // 将在页面加载时动态填充
  },
  {
    key: "billCode",
    label: "单据编号",
    placeholder: "请输入单据编号",
  },
  {
    key: "billStatus",
    label: "单据状态",
    type: "selector",
    placeholder: "请选择单据状态",
    options: ["草稿", "正文"],
  },
  {
    key: "workflowStatus",
    label: "状态",
    type: "selector",
    placeholder: "请选择状态",
    options: ["待提交", "提交中", "审核中", "已完成", "已取消"],
  },
];

// 定义操作按钮（只保留查看功能）
const actions = [
  {
    key: "view",
    label: "查看",
    icon: "eye",
    color: "#7881de",
    class: "view-btn",
  },
];

// 处理筛选事件
const handleFilter = async (filterParams: any) => {
  loading.value = true;
  try {
    const queryParams: any = {
      Limit: 9999, // 一次性获取所有数据
      Page: 1,
    };

    // 映射筛选参数到API参数
    if (filterParams.Name) {
      queryParams.Name = filterParams.Name;
    }
    // 处理辞退日期范围：确保结束日期包含当天的所有时间
    const dismissDateRange = processDateRangeField(filterParams, "dismissDate");
    if (dismissDateRange) {
      queryParams.DismissDate = dismissDateRange;
    }
    if (filterParams.resignType) {
      // 直接传递中文状态文本
      queryParams.ResignType = filterParams.resignType;
    }
    if (filterParams.approver) {
      queryParams.Approver = filterParams.approver;
    }
    // 处理审批时间范围：确保结束日期包含当天的所有时间
    const approvalTimeRange = processDateRangeField(
      filterParams,
      "approvalTime",
    );
    if (approvalTimeRange) {
      queryParams.ApprovalTime = approvalTimeRange;
    }
    if (filterParams.groupId) {
      queryParams.GroupId = filterParams.groupId;
    }
    if (filterParams.billCode) {
      queryParams.BillCode = filterParams.billCode;
    }
    if (filterParams.billStatus) {
      // 直接传递中文状态文本
      queryParams.BillStatus = filterParams.billStatus;
    }
    if (filterParams.workflowStatus) {
      // 直接传递中文状态文本
      queryParams.WorkflowStatus = filterParams.workflowStatus;
    }

    const response = await api.search(queryParams);

    if (response && response.Data) {
      dismissRequestList.value = response.Data;
    } else {
      dismissRequestList.value = [];
    }
  } catch (error) {
    dismissRequestList.value = [];

    // 显示错误提示
    uni.showToast({
      title: "筛选搜索失败，请稍后重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    loading.value = false;
  }
};

// 静默刷新数据获取函数（供XenListPage组件调用）
const silentRefreshFn = async () => {
  const response = await api.search({
    Limit: 9999, // 一次性获取所有数据
    Page: 1,
  });
  return response?.Data || [];
};

// 处理静默刷新结果
const handleSilentRefresh = (newData: ISysHrDismissRequestBillView[]) => {
  dismissRequestList.value = newData;
};

// 处理刷新事件
const handleRefresh = () => {
  // 只有在首次加载或明确需要刷新时才调用fetchData
  if (dismissRequestList.value.length === 0) {
    fetchData();
  }
};

// 加载状态
const loading = ref(false);

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    const response = await api.search({
      Limit: 9999, // 一次性获取所有数据
      Page: 1,
    });

    if (response && response.Data) {
      dismissRequestList.value = response.Data;
    } else {
      dismissRequestList.value = [];
    }
  } catch (error) {
    dismissRequestList.value = [];

    // 显示错误提示
    uni.showToast({
      title: "获取开除申请信息失败，请稍后重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    loading.value = false;
  }
};

// 加载部门数据
const loadDepartmentData = async () => {
  try {
    const departments = await commonApiInstance.GetParentsTree();
    // 找到部门筛选字段并设置数据
    const departmentField = filterFields.find(
      (field) => field.key === "groupId",
    );
    if (departmentField) {
      departmentField.departmentData = departments;
    }
  } catch (error) {
    console.error("加载部门数据失败:", error);
  }
};

// 页面挂载时执行
onMounted(() => {
  fetchData();
  loadDepartmentData();
});
</script>

<style scoped>
/* 页面样式 */
</style>
